var data = {
    collectlist: [],
    shopcarlist: []
}


//创建纯函数(reducer)
//作用 ：接收修改之前的旧state和action ，生成新的state，返回新的state
function reducer(state = data, action) {
    //深拷贝

    var newState = JSON.parse(JSON.stringify(state));

    //判断action的类型
    if (action.type === 'COLLECT') {//收藏
        newState.collectlist.push(action.params)
    } else if (action.type === 'CANCEL_COLLECT') {//取消收藏

        var index = newState.collectlist.findIndex((item) => {
            return item.id = action.params.id
        })
        if (index !== -1) {
            newState.collectlist.splice(index, 1)
        }
    } else if (action.type === 'SHOPPCAT_ADD') {//添加到购物车
        let shopindex=newState.shopcarlist.findIndex((item)=>{
            return item.id===action.params.id
        })
        if(shopindex!==-1){
            newState.shopcarlist[shopindex].count++;
        }else{
            action.params.count=1;
            newState.shopcarlist.push(action.params)
        }
        //购物车添加
    }else if(action.type==='SHOPPCAT_LIST'){
        newState.shopcarlist=action.params
    } else if(action.type==='SUB'){//购物车减一
        var shopindex=newState.shopcarlist.findIndex((item)=>{
            return item.id=action.params.id
        })
        if(newState.shopcarlist[shopindex].count>1){
            newState.shopcarlist[shopindex].count--;
        }else{
            newState.shopcarlist.splice(shopindex,1)
        }
    }
    else {
        newState = state

    }
    console.log(newState);
    return newState

}
export default reducer;